//------------------------------------------------------------------------------ 
// <copyright file="JDialog.cs" company="Fm Computer">
//     Copyright (c) Fm Computer di Menatti Fulvia.  All rights reserved.
// </copyright>
//----------------------------------------------------------------------------- 
namespace FmjQuery
{
    using System.ComponentModel;
    using System.Text;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    /// <summary>
    /// jQuery dialog Control
    /// </summary>
    [ToolboxData("<{0}:JDialog runat=server VerticalAlign=center HorizontalAlign=center ></{0}:JDialog>")]
    public class JDialog : JQueryBaseControl, IResizeDimension, INamingContainer
    {
        #region Fields

        /// <summary>
        /// Format of dialog id
        /// </summary>
        private const string FORMATID = "{0}_Dialog";

        /// <summary>
        /// List of buttons
        /// </summary>
        private DialogButtons tbuttons;
        #endregion

        #region Costruct
        /// <summary>
        /// Initializes a new instance of the JDialog class.
        /// </summary>
        public JDialog()
        {
            this.IsRenderControl = true;
        }
        #endregion

        #region Property

        /// <summary>
        /// Gets or sets id of control that open dialog
        /// </summary>
        public string OpenControlID 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets or sets a value indicating whether openControl is client
        /// </summary>
        public bool IsClientOpenControl 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets or sets a value indicating whether dialog will open automatically when dialog is called. If false it will stay hidden until .dialog("open") is called on it
        /// </summary>
        public bool AutoOpen
        {
            get;
            set;
        }

        /// <summary>
        /// Gets list of button
        /// </summary>
        public DialogButtons Buttons
        {
            get
            {
                if (this.tbuttons == null)
                {
                    this.tbuttons = new DialogButtons();
                }

                return this.tbuttons;
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether close dialog with ESC key
        /// </summary>
        public bool CloseOnEscape
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether control is draggable
        /// </summary>
        public bool IsDraggable
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets maximun height
        /// </summary>
        public int MaxHeight
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets max of width
        /// </summary>
        public int MaxWidth
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets min of height
        /// </summary>
        public int MinHeight
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets min of width
        /// </summary>
        public int MinWidth
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether dialog is modal
        /// </summary>
        public bool IsModal 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets or sets type of vertical align
        /// </summary>
        [DefaultValue("center")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public Align VerticalAlign
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets type of Horizontal Align
        /// </summary>
        [DefaultValue("center")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public Align HorizontalAlign 
        { 
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether dialog is resizable
        /// </summary>
        public bool IsResizable 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets or sets a value indicating whether the dialog will stack on top of other dialogs. This will cause the dialog to move to the front of other dialogs when it gains focus
        /// </summary>
        public bool Stack 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets or sets Title
        /// </summary>
        public string Title 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets or sets z-index
        /// </summary>
        public int ZIndex 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets or sets name of client function that call when change status
        /// </summary>
        public string ClientOnChange 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets or sets Content Template Control
        /// </summary>
        [Browsable(false)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [TemplateContainer(typeof(JDialog))]
        public virtual ITemplate ContentTemplate
        {
            get;
            set;
        }

        /// <summary>
        /// Gets content container
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Control ContentContainer
        {
            get;
            private set;
        }
        #endregion

        #region Overrides of JQueryExtendControl
        /// <summary>
        /// Return list of webResource
        /// </summary>
        /// <returns>web resources</returns>
        public override JWebSources GetResources()
        {
            return null;
        }

        /// <summary>
        /// Gets list of css image resources
        /// </summary>
        /// <returns>list of images</returns>
        public override CssResources GetCssResources()
        {
            return null;
        }

        /// <summary>
        /// Gets list of client nameSpace
        /// </summary>
        /// <returns>list of namespace</returns>
        public override ClientNameSpaces GetClientNameSpace()
        {
            return null;
        }

        /// <summary>
        /// Create jQuery control
        /// </summary>
        public override void CreateJControl()
        {
            if (this.Enabled)
            {
                // required script
                this.Manager.Dialog = true;

                // create script
                StringBuilder builder = new StringBuilder("jQuery(function($) {");
                bool is6 = this.Page.Request.UserAgent.Contains("MSIE 6.0");
                bool is8 = this.Page.Request.UserAgent.Contains("MSIE 8.0");

                builder.AppendFormat("$('#{0}').dialog(", string.Format(FORMATID, this.ClientID));
                builder.Append("{");
                builder.AppendFormat("position: ['{0}','{1}'],autoOpen: {2}", this.HorizontalAlign, this.VerticalAlign, this.AutoOpen ? "true" : "false");

                // check if IE 6 or IE 8
                if (is6 || is8)
                {
                    this.Manager.BgFrame = true;
                    builder.Append(",bgiframe: true");
                }

                // buttons
                if (this.Buttons.Count > 0)
                {
                    builder.Append(",buttons: {");

                    bool first = true;
                    foreach (DialogButton button in this.tbuttons)
                    {
                        if (!first)
                        {
                            builder.Append(",");
                        }
                        else
                        {
                            first = false;
                        }

                        builder.AppendFormat("{0}: {1}", button.Text, button.ClientFunction);
                    }

                    builder.Append("}");
                }

                if (this.CloseOnEscape)
                {
                    builder.Append(",closeOnEscape: true");
                }

                if (!string.IsNullOrEmpty(this.CssClass))
                {
                    builder.AppendFormat(",dialogClass: '{0}'", this.CssClass);
                }

                if (this.IsDraggable)
                {
                    this.Manager.Draggable = true;
                    builder.Append(",draggable: true");
                }

                if (this.Height.Value > 0.0d)
                {
                    builder.AppendFormat(",height: {0}", this.Height);
                }

                if (this.MaxHeight > 0)
                {
                    builder.AppendFormat(",maxHeight: {0}", this.MaxHeight);
                }

                if (this.MaxWidth > 0)
                {
                    builder.AppendFormat(",maxwidth: {0}", this.MaxWidth);
                }

                if (this.MinHeight > 0)
                {
                    builder.AppendFormat(",minHeight: {0}", this.MinHeight);
                }

                if (this.MinWidth > 0)
                {
                    builder.AppendFormat(",minWidth: {0}", this.MinWidth);
                }

                if (this.IsModal && !is8)
                {
                    builder.Append(",modal: true");
                }

                if (this.IsResizable)
                {
                    this.Manager.Resizable = true;
                    builder.Append(",resizable: true");
                }

                if (this.Stack)
                {
                    builder.Append(",stack: true");
                }

                if (!string.IsNullOrEmpty(this.Title))
                {
                    builder.AppendFormat(",title: '{0}'", this.Title.ParseStringToClient());
                }

                if (this.Width.Value > 0.0d)
                {
                    builder.AppendFormat(",width: {0}", this.Width);
                }

                if (this.ZIndex > 0)
                {
                    builder.AppendFormat(",zIndex: {0}", this.ZIndex);
                }

                if (!string.IsNullOrEmpty(this.ClientOnChange))
                {
                    builder.AppendFormat(",change: {0}", this.ClientOnChange);
                }

                builder.Append("});});");

                if (!string.IsNullOrEmpty(this.OpenControlID))
                {
                    this.Manager.FrameWorkExtend = true;
                    builder.AppendFormat("$('#{0}').first('onclick', function(e)", this.IsClientOpenControl ? this.OpenControlID : this.Page.FindControl(this.OpenControlID).ClientID);
                    builder.Append("{");
                    builder.AppendFormat("$('#{0}').dialog('open');return false;", string.Format(FORMATID, this.ClientID));
                    builder.Append("}, true);");
                }

                Utility.RegisterStartUpScript(this.Page, string.Concat("Dialog_", this.ClientID), builder.ToString());
            }
        }
        #endregion

        #region Override
        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            this.Controls.Clear();

            this.ContentContainer = new PlaceHolder();

            ITemplate ctemplate = this.ContentTemplate ?? new ContentDialogTemplate();

            ctemplate.InstantiateIn(this.ContentContainer);

            this.Controls.Add(this.ContentContainer);
        }

        /// <summary>
        /// Renders the control to the specified HTML writer.
        /// </summary>
        /// <param name="writer">The System.Web.UI.HtmlTextWriter object that receives the control content.</param>
        protected override void Render(HtmlTextWriter writer)
        {
            new LiteralControl(string.Format("<div id='{0}'>", string.Format(FORMATID, this.ClientID))).RenderControl(writer);

            this.ContentContainer.RenderControl(writer);

            new LiteralControl("</div>").RenderControl(writer);
        }
        #endregion
    }
}